package com.thinkit.cms.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thinkit.cms.api.admin.DictService;
import com.thinkit.cms.dto.admin.DictDto;
import com.thinkit.cms.entity.admin.Dict;
import com.thinkit.cms.mapper.admin.DictMapper;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.utils.model.Tree;
import com.thinkit.utils.utils.BuildTree;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author LG
 * @since 2019-08-29
 */
@Service
public class DictServiceImpl extends BaseServiceImpl<DictDto, Dict, DictMapper> implements DictService {


    @Override
    public List<DictDto> listType(DictDto v) {
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.groupBy("type").select("type");
        return ResultT2D(list(queryWrapper));
    }

	@Override
	public List<DictDto> listByType(String type) {
		  QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
		  queryWrapper.eq("type", type).notIn("parent_id", 0);
		  return ResultT2D(this.baseMapper.selectList(queryWrapper));
	}

    @Override
    public Tree<DictDto> treeList(DictDto dto) {
        List<DictDto> dicts = listDto(dto);
        if (dicts != null && !dicts.isEmpty()) {
            List<Tree<DictDto>> trees = new ArrayList<Tree<DictDto>>();
            for (DictDto dictDto : dicts) {
                Tree<DictDto> tree = new Tree<DictDto>();
                tree.setId(dictDto.getId());
                tree.setKey(dictDto.getValue());
                tree.setParentId(dictDto.getParentId());
                tree.setName(dictDto.getName());
                tree.setSpread(true);
                Map<String, Object> attributes = new HashMap<>(16);
                attributes.put("type", dictDto.getType());
                attributes.put("num", dictDto.getNum());
                attributes.put("remarks", dictDto.getRemarks());
                tree.setAttributes(attributes);
                trees.add(tree);
            }
            Tree<DictDto> t = BuildTree.build(trees);
            return t;
        } else {
            return null;
        }
    }
}
